package com.ask.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ask.dto.UserLoginDTO;
import com.ask.entity.User;
import com.ask.exception.BaseException;
import com.ask.mapper.UserMapper;
import com.ask.properties.WeChatProperties;
import com.ask.service.UserService;
import com.ask.utils.HttpClientUtil;
import com.ask.vo.UserReportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 获取当前用户的openId
        String openid = getOpenid(userLoginDTO.getCode());
        if (openid == null) {
            throw new BaseException("微信用户登录失败！");
        }

        // 判断当前用户是否是新用户
        User user = userMapper.getByOpenId(openid);

        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        return user;
    }

    /**
     * 获取最近7天活跃用户
     * todo 待完善
     * @return
     */
    @Override
    public List<Long> getActiveUsersLast7Days() {
        return Collections.singletonList(4L);
    }


    private String getOpenid(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String appid = weChatProperties.getAppid();
        String secret = weChatProperties.getSecret();

        // 通过 HttpClientUtil.doGet 方法发送 GET 请求
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

}
